package cn.ibizlab.eam.core.eam_core.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.eam.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.eam.core.eam_core.domain.EMPODetail;
import cn.ibizlab.eam.core.eam_core.filter.EMPODetailSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMPODetailService;

import cn.ibizlab.eam.util.helper.CachedBeanCopier;
import cn.ibizlab.eam.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.eam.core.eam_core.mapper.EMPODetailMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[订单条目] 服务对象接口实现
 */
@Slf4j
@Service("EMPODetailServiceImpl")
public class EMPODetailServiceImpl extends ServiceImpl<EMPODetailMapper, EMPODetail> implements IEMPODetailService {

    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemRInService emitemrinService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMItemService emitemService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMPOService empoService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_core.service.IEMWPListService emwplistService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFEmpService pfempService;
    @Autowired
    @Lazy
    protected cn.ibizlab.eam.core.eam_pf.service.IPFUnitService pfunitService;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(EMPODetail et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmpodetailid()), et);
        return true;
    }

    @Override
    @Transactional
    public void createBatch(List<EMPODetail> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list, batchSize);
    }

    @Override
    @Transactional
    public boolean update(EMPODetail et) {
        fillParentData(et);
        if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("empodetailid", et.getEmpodetailid()))) {
            return false;
        }
        CachedBeanCopier.copy(get(et.getEmpodetailid()), et);
        return true;
    }

    @Override
    @Transactional
    public void updateBatch(List<EMPODetail> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list, batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result = removeById(key);
        return result ;
    }

    @Override
    @Transactional
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public EMPODetail get(String key) {
        EMPODetail et = getById(key);
        if(et == null){
            et = new EMPODetail();
            et.setEmpodetailid(key);
        }
        else {
        }
        return et;
    }

    @Override
    public EMPODetail getDraft(EMPODetail et) {
        fillParentData(et);
        return et;
    }

    @Override
    @Transactional
    public EMPODetail check(EMPODetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean checkBatch(List<EMPODetail> etList) {
        for(EMPODetail et : etList) {
            check(et);
        }
        return true;
    }

    @Override
    public boolean checkKey(EMPODetail et) {
        return (!ObjectUtils.isEmpty(et.getEmpodetailid())) && (!Objects.isNull(this.getById(et.getEmpodetailid())));
    }
    @Override
    @Transactional
    public EMPODetail createRin(EMPODetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean createRinBatch(List<EMPODetail> etList) {
        for(EMPODetail et : etList) {
            createRin(et);
        }
        return true;
    }

    @Override
    @Transactional
    public EMPODetail genId(EMPODetail et) {
        //自定义代码
        return et;
    }

    @Override
    @Transactional
    public boolean genIdBatch(List<EMPODetail> etList) {
        for(EMPODetail et : etList) {
            genId(et);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean save(EMPODetail et) {
        if(!saveOrUpdate(et)) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(EMPODetail et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? getProxyService().update(et) : getProxyService().create(et);
        }
    }

    @Override
    @Transactional
    public boolean saveBatch(Collection<EMPODetail> list) {
        list.forEach(item->fillParentData(item));
        List<EMPODetail> create = new ArrayList<>();
        List<EMPODetail> update = new ArrayList<>();
        for (EMPODetail et : list) {
            if (ObjectUtils.isEmpty(et.getEmpodetailid()) || ObjectUtils.isEmpty(getById(et.getEmpodetailid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
        return true;
    }

    @Override
    @Transactional
    public void saveBatch(List<EMPODetail> list) {
        list.forEach(item->fillParentData(item));
        List<EMPODetail> create = new ArrayList<>();
        List<EMPODetail> update = new ArrayList<>();
        for (EMPODetail et : list) {
            if (ObjectUtils.isEmpty(et.getEmpodetailid()) || ObjectUtils.isEmpty(getById(et.getEmpodetailid()))) {
                create.add(et);
            } else {
                update.add(et);
            }
        }
        if (create.size() > 0) {
            getProxyService().createBatch(create);
        }
        if (update.size() > 0) {
            getProxyService().updateBatch(update);
        }
    }


	@Override
    public List<EMPODetail> selectByItemid(String emitemid) {
        return baseMapper.selectByItemid(emitemid);
    }
    @Override
    public void removeByItemid(String emitemid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("itemid",emitemid));
    }

	@Override
    public List<EMPODetail> selectByPoid(String empoid) {
        return baseMapper.selectByPoid(empoid);
    }
    @Override
    public void removeByPoid(String empoid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("poid",empoid));
    }

	@Override
    public List<EMPODetail> selectByWplistid(String emwplistid) {
        return baseMapper.selectByWplistid(emwplistid);
    }
    @Override
    public void removeByWplistid(String emwplistid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("wplistid",emwplistid));
    }

	@Override
    public List<EMPODetail> selectByEmpid(String pfempid) {
        return baseMapper.selectByEmpid(pfempid);
    }
    @Override
    public void removeByEmpid(String pfempid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("empid",pfempid));
    }

	@Override
    public List<EMPODetail> selectByRempid(String pfempid) {
        return baseMapper.selectByRempid(pfempid);
    }
    @Override
    public void removeByRempid(String pfempid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("rempid",pfempid));
    }

	@Override
    public List<EMPODetail> selectByRunitid(String pfunitid) {
        return baseMapper.selectByRunitid(pfunitid);
    }
    @Override
    public void removeByRunitid(String pfunitid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("runitid",pfunitid));
    }

	@Override
    public List<EMPODetail> selectByUnitid(String pfunitid) {
        return baseMapper.selectByUnitid(pfunitid);
    }
    @Override
    public void removeByUnitid(String pfunitid) {
        this.remove(new QueryWrapper<EMPODetail>().eq("unitid",pfunitid));
    }


    /**
     * 查询集合 已关闭
     */
    @Override
    public Page<EMPODetail> searchClosed(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchClosed(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<EMPODetail> searchDefault(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 近五年采购
     */
    @Override
    public Page<Map> searchLaterYear(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Map> pages=baseMapper.searchLaterYear(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Map>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 主单订单明细查询
     */
    @Override
    public Page<EMPODetail> searchMain2(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchMain2(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待记账
     */
    @Override
    public Page<EMPODetail> searchWaitBook(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchWaitBook(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 待验收
     */
    @Override
    public Page<EMPODetail> searchWaitCheck(EMPODetailSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EMPODetail> pages=baseMapper.searchWaitCheck(context.getPages(),context,context.getSelectCond());
        return new PageImpl<EMPODetail>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(EMPODetail et){
        //实体关系[DER1N_EMPODETAIL_EMITEM_ITEMID]
        if(!ObjectUtils.isEmpty(et.getItemid())){
            cn.ibizlab.eam.core.eam_core.domain.EMItem item=et.getItem();
            if(ObjectUtils.isEmpty(item)){
                cn.ibizlab.eam.core.eam_core.domain.EMItem majorEntity=emitemService.get(et.getItemid());
                et.setItem(majorEntity);
                item=majorEntity;
            }
            et.setSunitid(item.getUnitid());
            et.setSunitname(item.getUnitname());
            et.setItemname(item.getEmitemname());
            et.setAvgprice(item.getPrice());
            et.setItembtypeid(item.getItembtypeid());
        }
        //实体关系[DER1N_EMPODETAIL_EMPO_POID]
        if(!ObjectUtils.isEmpty(et.getPoid())){
            cn.ibizlab.eam.core.eam_core.domain.EMPO po=et.getPo();
            if(ObjectUtils.isEmpty(po)){
                cn.ibizlab.eam.core.eam_core.domain.EMPO majorEntity=empoService.get(et.getPoid());
                et.setPo(majorEntity);
                po=majorEntity;
            }
            et.setLabservicename(po.getLabservicename());
            et.setPowfstep(po.getWfstep());
            et.setLabserviceid(po.getLabserviceid());
            et.setPostate(po.getPostate());
            et.setPoname(po.getEmponame());
            et.setPorempname(po.getRempname());
            et.setPorempid(po.getRempid());
        }
        //实体关系[DER1N_EMPODETAIL_EMWPLIST_WPLISTID]
        if(!ObjectUtils.isEmpty(et.getWplistid())){
            cn.ibizlab.eam.core.eam_core.domain.EMWPList wplist=et.getWplist();
            if(ObjectUtils.isEmpty(wplist)){
                cn.ibizlab.eam.core.eam_core.domain.EMWPList majorEntity=emwplistService.get(et.getWplistid());
                et.setWplist(majorEntity);
                wplist=majorEntity;
            }
            et.setUseto(wplist.getUseto());
            et.setObjid(wplist.getObjid());
            et.setEquips(wplist.getEquips());
            et.setEquipid(wplist.getEquipid());
            et.setWplistname(wplist.getEmwplistname());
            et.setTeamid(wplist.getTeamid());
            et.setObjname(wplist.getObjname());
            et.setEquipname(wplist.getEquipname());
        }
        //实体关系[DER1N_EMPODETAIL_PFEMP_EMPID]
        if(!ObjectUtils.isEmpty(et.getEmpid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp pfempid=et.getPfempid();
            if(ObjectUtils.isEmpty(pfempid)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getEmpid());
                et.setPfempid(majorEntity);
                pfempid=majorEntity;
            }
            et.setEmpname(pfempid.getEmpinfo());
        }
        //实体关系[DER1N_EMPODETAIL_PFEMP_REMPID]
        if(!ObjectUtils.isEmpty(et.getRempid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFEmp pferempid=et.getPferempid();
            if(ObjectUtils.isEmpty(pferempid)){
                cn.ibizlab.eam.core.eam_pf.domain.PFEmp majorEntity=pfempService.get(et.getRempid());
                et.setPferempid(majorEntity);
                pferempid=majorEntity;
            }
            et.setRempname(pferempid.getEmpinfo());
        }
        //实体关系[DER1N_EMPODETAIL_PFUNIT_RUNITID]
        if(!ObjectUtils.isEmpty(et.getRunitid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFUnit runit=et.getRunit();
            if(ObjectUtils.isEmpty(runit)){
                cn.ibizlab.eam.core.eam_pf.domain.PFUnit majorEntity=pfunitService.get(et.getRunitid());
                et.setRunit(majorEntity);
                runit=majorEntity;
            }
            et.setRunitname(runit.getPfunitname());
        }
        //实体关系[DER1N_EMPODETAIL_PFUNIT_UNITID]
        if(!ObjectUtils.isEmpty(et.getUnitid())){
            cn.ibizlab.eam.core.eam_pf.domain.PFUnit unit=et.getUnit();
            if(ObjectUtils.isEmpty(unit)){
                cn.ibizlab.eam.core.eam_pf.domain.PFUnit majorEntity=pfunitService.get(et.getUnitid());
                et.setUnit(majorEntity);
                unit=majorEntity;
            }
            et.setUnitname(unit.getPfunitname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<EMPODetail> getEmpodetailByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<EMPODetail> getEmpodetailByEntities(List<EMPODetail> entities) {
        List ids =new ArrayList();
        for(EMPODetail entity : entities){
            Serializable id=entity.getEmpodetailid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0) {
            return this.listByIds(ids);
        }
        else {
            return entities;
        }
    }


    public IEMPODetailService getProxyService() {
        return cn.ibizlab.eam.util.security.SpringContextHolder.getBean(this.getClass());
    }
}



